//
//  BaseWebViewController.swift
//  Lease_IOS
//
//  Created by Mr.wang on 2018/12/20.
//  Copyright © 2018 Mr.wang. All rights reserved.
//

import UIKit
import WebKit
import RxWebKit
import RxSwift
import RxCocoa
import MJRefresh
import YBImageBrowser

class BaseWebViewController: BaseUIViewController {
    
    var webView: WKWebView!
    let progressView = WebViewProgressView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 2))
    let errorView = WebViewErrorView()
    
    var url: String
    var previewImages: [String] = []
    
    init(url: String) {
        self.url = url
        super.init(nibName: nil, bundle: nil)
        
        let config = WKWebViewConfiguration()
        config.preferences.javaScriptCanOpenWindowsAutomatically = true
        config.allowsInlineMediaPlayback = true
        
        webView = WKWebView(frame: .zero, configuration: config)
        webView.navigationDelegate = self;
        webView.uiDelegate = self;
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupView()
        setupWebView()
        loadWebUrl()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        errorView.center = CGPoint(x: SCREEN_WIDTH * 0.5, y: 80)
    }
    
    func setupView() {
        self.view.backgroundColor = UIColor.white
        webView.scrollView.contentInsetAdjustmentBehavior = .never
        
        webView.allowsLinkPreview = false
        webView.scrollView.decelerationRate = .normal
        webView.backgroundColor = UIColor.white
        webView.scrollView.showsHorizontalScrollIndicator = false
        self.view.addSubview(webView)
        webView.snp.makeConstraints { (make) in
            make.left.top.right.bottom.equalTo(0)
        }
        let refreshHeader = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            self?.loadWebUrl()
        })
//        refreshHeader.lastUpdatedTimeLabel?.isHidden = true;
        refreshHeader.lastUpdatedTimeLabel?.isHidden = true
        webView.scrollView.mj_header = refreshHeader
        
        errorView.isHidden = true
        webView.scrollView.addSubview(errorView)
        
        self.view.addSubview(progressView)
    }
    
    func setupWebView() {
        webView.rx.title.map{ $0 ?? "" }
            .bind(to: navigationItem.rx.title)
            .disposed(by: rx.disposeBag)
        
        webView.rx.estimatedProgress.asObservable()
            .bind(to: progressView.rx.progress)
            .disposed(by: rx.disposeBag)
        
        let webLoading = webView.rx.loading.share(replay: 1)
        
        webLoading
            .bind(to: progressView.rx.loading)
            .disposed(by: rx.disposeBag)
        
        webLoading
            .bind(to: UIApplication.shared.rx.isNetworkActivityIndicatorVisible)
            .disposed(by: rx.disposeBag)
        
        webLoading.bind(to: (webView.scrollView.mj_header?.rx.isRefreshing)!)
            .disposed(by: rx.disposeBag)
    }
    
    func loadWebUrl() {
        guard let url = URL.init(string: url) else { return }
        webView.load(URLRequest.init(url: url))
    }
    
    deinit {
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
    }
}

extension BaseWebViewController: WKNavigationDelegate, WKUIDelegate {
 
//    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) {
//        
//    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
//        print("页面加载完成")
        let delayTime = DispatchTime.now() + 3.0; // 3秒
        DispatchQueue.main.asyncAfter(deadline: delayTime) {
//            print("2秒后开始执行")
            
            let js = """
            (function () {
              var linksToHide = [
                "https://www.facebook.com/aesolarenergy/",
                "https://www.linkedin.com/company/ae-solar/",
                "https://www.instagram.com/aesolarenergy/",
                "https://twitter.com/aesolar_energy/",
                "https://www.youtube.com/@AESOLAR/featured/"
              ];

              var anchors = document.getElementsByTagName("a");

              for (var i = 0; i < anchors.length; i++) {
                var a = anchors[i];
                var href = a.getAttribute("href");
                if (href && linksToHide.indexOf(href) > -1) {
                  a.style.display = "none";
                }
              }
            })();
            """
            webView.evaluateJavaScript(js, completionHandler: nil)
            
        }
    }
    
}












